from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosDining, collectionDiningList, collectionStallDeviceList
from app.globals.uuidTool import getuuId
from app.db.dbUserManage import getUserNameByuserId
from app.globals.publicMethod import globalGetNowTime
from app.db.dbDishQuery import queryIsHaveDishes

def createStall(diningNo, stallName, stallDesc, userId):
    '''
    创建餐厅档口
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo}
        collection = mg_client[dbSynPosDining][collectionDiningList]
        res = collection.find_one(cond)
        if res is None:
           return None
           
        newList = []
        #如果该餐厅的该档口存在
        tempres = res.get('stallList')
        if tempres is not None and len(tempres) > 0:
            newList = tempres
            for v in tempres:
                if v['stallName'] == stallName:
                    return False

        stallNo = getuuId()
        now = globalGetNowTime()
        username = getUserNameByuserId(userId)
        data = {
            'stallNo': stallNo,
            'stallName': stallName,
            'stallDesc': stallDesc,
            'createTime': now,
            'updateTime': now,
            'creatorUserName': username, 
            'editorUserName': username,
            
        }
        newList.append(data)
        collection.find_one_and_update(cond, 
                        {'$set': 
                            {'stallList': newList}
                        })

        return stallNo

    except Exception as e:
        raise ErrMongoClient.data(str(e))


def editStall(diningNo, stallNo, stallName, stallDesc, userId):
    '''
    编辑档口
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDining][collectionDiningList]
        cond = {'diningNo': diningNo}
        res = collection.find_one(cond)
        #如果该餐厅不存在
        if res is None:
            return None

        newList = res['stallList']
        if newList is None or len(newList) <= 0:
            return None

        #如果该餐厅的该档口id存在
        for n, v in enumerate(newList):          
            if v['stallNo'] == stallNo:
                now = globalGetNowTime()
                username = getUserNameByuserId(userId)
                newList[n]['stallNo'] = stallNo
                newList[n]['stallName'] = stallName
                newList[n]['stallDesc'] = stallDesc
                newList[n]['updateTime'] = now
                newList[n]['editorUserName'] = username    
                return collection.find_one_and_update(cond, 
                                    {'$set': 
                                        {'stallList': newList}                                
                                    })

        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def delStall(diningNo, stallNo):
    '''
    删除档口
    '''
    try:  
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDining][collectionDiningList]
        cond = {'diningNo': diningNo}
        res = collection.find_one(cond)
        # 如果该餐厅不存在
        if res is None:
            return None

        newList = res['stallList']
        if newList is None or len(newList) <= 0:
            return None
        
        # 如果该餐厅该档口下有菜则不让删除
        if queryIsHaveDishes(diningNo, stallNo) is True:
            return False 
        
        for n, v in enumerate(newList):
            # 如果该餐厅的该档口id存在
            if v['stallNo'] == stallNo:
                newList.remove(v)
                return collection.find_one_and_update(cond, 
                                    {'$set': 
                                        {'stallList': newList}
                                    })

        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))

def posReport(diningNo, stallNo, deviceNo, deviceType, softVersion, skj130No):
    '''
    档口点餐机信息上报
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDining][collectionStallDeviceList]
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = collection.find_one(cond)
        # 如果collectionStallDeviceList表里该餐厅该档口不存在
        if res is None:
            deviceList = []
            data = {
                'deviceNo': deviceNo,
                'deviceType': deviceType,
                'softVersion': softVersion,
                'skj130No': skj130No,
                'updateTime': globalGetNowTime(),
                'upgradeState': ''
            }
            deviceList.append(data)
            info ={
                'diningNo': diningNo,
                'stallNo': stallNo,
                'deviceList': deviceList
            }
            return collection.insert_one(info)

        conds = {'diningNo': diningNo, 'stallNo': stallNo}
        now = globalGetNowTime()
        newList = res['deviceList']
        # 如果该设备存在
        for n, v in enumerate(newList):          
            if v['deviceNo'] == deviceNo:
                newList[n]['deviceType'] = deviceType
                newList[n]['softVersion'] = softVersion
                newList[n]['skj130No'] = skj130No
                newList[n]['updateTime'] = now
                return collection.find_one_and_update(conds,
                                        {'$set': 
                                            {'deviceList': newList}                               
                                        })

        # 如果该设备不存在
        data = {
            'deviceNo': deviceNo,
            'deviceType': deviceType,
            'softVersion': softVersion,
            'skj130No': skj130No,
            'updateTime': globalGetNowTime(),
            'upgradeState': ''
        }
        newList.append(data)
        return collection.find_one_and_update(conds,
                                 {'$set': 
                                    {'deviceList': newList}                               
                                 })

    except Exception as e:
        raise ErrMongoClient.data(str(e))


def posSetUpdateStatus(diningNo, stallNo, deviceNo, updateStatus):
    '''
    点餐机升级设置
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDining][collectionStallDeviceList]
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = collection.find_one(cond)
        #如果该餐厅不存在
        if res is None:
            return None

        deviceList = res['deviceList']
        if deviceList is None or len(deviceList) <= 0:
            return None
       
        #如果该设备存在
        for n, v in enumerate(deviceList):          
            if v['deviceNo'] == deviceNo:
                deviceList[n]['updateStatus'] = updateStatus
                return collection.find_one_and_update(cond, 
                                    {'$set': 
                                        {'deviceList': deviceList}                                  
                                    })

        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))